'use strict';

const bcrypt = require('bcryptjs');
const { Service } = require('egg');
const { Op } = require('sequelize');

class ScoreService extends Service {
  /**
   * 根据分页和搜索条件获取课程分数
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条

   */
  async getPage(where, page, pageSize) {
    const { Score, Student, Course,Teacher } = this.ctx.model;
    try {
        const res = Score.findAndCountAll({
            where: {
                ...where
            },
            order:[
                // id 降序
                ['created_at','DESC']
            ],
            include: [
                {model: Student, as: 'student'},
                {model: Course, as: 'course'},
                {model: Teacher, as: 'teacher'},
            ],
            offset: pageSize * (page - 1),
            limit: pageSize,
        });
        return res
    } catch (e) {
        console.log('00000', e)
    }
  }

  /**
   * 注册用户数据
   * @param {Object} data
   */
  async createItem(data) {
    const { Score } = this.ctx.model;
    const userExists = await Score.findOne({
      attributes: ['course_id', 'student_id'],
      where: {
        [Op.and]: {
            course_id: data.course_id,
            student_id: data.student_id,
        },
      },
    });
      console.log('userExists', userExists)
    if (userExists) throw new Error('该学生该课程已经打分');
    const newUser = await Score.create(data);
    return newUser.dataValues;
  }

  /**
   * 根据id删除对应的用户
   * @param {Number} uid
   */
  async deleteItemById(id) {
    return await this.ctx.model.Score.destroy({ where: { id } });
  }

  /**
   * 根据ID修改用户信息
   * @param {Number} id 用户ID
   * @param {Object} data 要修改的用户信息
   */
  async updateItemById(id, data) {
    const { Score } = this.ctx.model;
    const { score_name } = data;
    const andWhere = { id: { [Op.ne]: id } };
    let neenCheck = false;
   if (score_name) {
      neenCheck = true;
      andWhere.score_name = score_name;
    }

    if (neenCheck) {
      const userExists = await Score.findOne({
        attributes: ['id'],
        where: { [Op.and]: andWhere },
      });
      if (userExists) throw new Error('该账号已经存在');
    }

    return await Score.update(data, { where: { id } });
  }
  // 所有列表
  async allList(where) {
    const { Score } = this.ctx.model;
    return Score.findAll({
      where
    });
  }
}

module.exports = ScoreService;
